package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权
        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();

        int userId = user.getId();

        Set<String> roles = sysUserService.findRolesByUserId(userId);
        Set<String> perms = sysUserService.findPermsByUserId(userId);


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //认证
        //获取用户输入的用户名和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        SysUsers user = sysUserService.findByUsername(username);

        if(user == null){
            throw new UnknownAccountException("账号不存在");
        }

        if(password == null && !password.equalsIgnoreCase(user.getPassword())){
            throw new IncorrectCredentialsException("输入密码错误");
        }

        if(user.getStatus() != 1){
            throw new LockedAccountException("账户已锁定,请联系管理员");
        }

        /**
         * 参数一：把用户对象信息存储到shiro内部
         * 参数二：密码
         * 参数三：自定义realm名称
         */
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, user.getRealname());


        return authenticationInfo;
    }
}
